package server;

import java.rmi.*;
import java.rmi.server.*;
import java.util.*;

import service.Product;
import service.Warehouse;

/**
 * This class is the implementation for the remote Warehouse interface. It is
 * located on the server.
 * 
 * This class is the target of remote method calls because it extends
 * UnicastRemoteObject. The constructor of UnicastRemoteObject makes objects
 * remotely accessible. If you don't use this inheritance, you would make this
 * call instead in the constructor of the remote object:
 * UnicastRomoteObject.exportObject(this, 0); 0 indicates that any suitable port
 * can be used to liste to client connections
 * 
 * The Unicast term indicates that the remote object is located by making a call
 * to a single IP address and port.
 */
public class WarehouseImpl extends UnicastRemoteObject implements Warehouse {

	private static final long serialVersionUID = 1526281044102879897L;

	/**
	 * Constructs a warehouse implementation. Super class constructor also
	 * throws a RemoteException.
	 */
	public WarehouseImpl(Warehouse backup) throws RemoteException {
		products = new HashMap<String, Product>();
		this.backup = backup;
	}

	public void add(String keyword, Product product) {
		product.setLocation(this);
		products.put(keyword, product);
	}

	public double getPrice(String description) throws RemoteException {
		System.out.println("Got request to find price for product " + description);
		for (Product p : products.values())
			if (p.getDescription().equals(description))
				return p.getPrice();
		if (backup == null)
			return 0;
		else
			return backup.getPrice(description);
	}

	public Product getProduct(List<String> keywords) throws RemoteException {
		System.out.println("Got request to find products: " + keywords.toString());
		for (String keyword : keywords) {
			Product p = products.get(keyword);
			if (p != null)
				return p;
		}
		if (backup != null)
			return backup.getProduct(keywords);
		else if (products.values().size() > 0)
			return products.values().iterator().next();
		else
			return null;
	}

	private Map<String, Product> products;
	private Warehouse backup;
}
